<template>
  <div>
    <div class="user" v-for="item in listClients" @click="event(item)">
      {{ item }}
    </div>
    <video style="width:240px;height:200px" ref="localPreview" autoplay></video>
    <video style="width:240px;height:200px" ref="remotePreview" 
    muted
    controls
    autoplay></video>
  </div>
</template>

<script>
import socket from "@/plugins/socketIO";

export default {
  data() {
    return {
      listClients: [],
      sender: "",
      offerPc: "",
      answerPc:"",
      dataChannel:"",
      shareData:new Map()
    };
  },
  created() {
    socket.on("listClients", (data) => {
      (this.listClients = data), (this.sender = data[0]);
    });
    this.receiveOffer();
    this.receiveAnswer();
    this.receiveOfferIce();
    this.receiveAnswerOfferIce();
  },
  
  async mounted(){
    let media = await navigator.mediaDevices.getUserMedia({video:true,audio:false})
    console.log(media.getTracks());
    this.$refs.localPreview.srcObject = media;
    this.shareData.set('localMediaStream',media);

    let remoteStream = new MediaStream();
    this.shareData.set('remoteMediaStream',remoteStream)
    console.log(remoteStream);
    
    this.$refs.remotePreview.srcObject = remoteStream;
  },
  methods: {
    // 1.发送者
    async event(receiver) {
      let offerPc = new RTCPeerConnection();
      this.shareData.set("offerPc", offerPc);

      // 发送ice(只要本地代理ICE 需要通过信令服务器传递信息给其他对等端时就会触发)
      offerPc.onicecandidate = (e) => {
        console.log('发送者offerPc.onicecandidate:',e);
        if (e.candidate) {
          socket.emit("offerIce", {
            receiver: receiver,
            ice: e.candidate,
          });
        }
      };

      // 把远程媒体流传入轨道中
      let remoteStream = this.shareData.get("remoteMediaStream");
      offerPc.ontrack = (e) => {
        console.log('',e);
        
        remoteStream.addTrack(e.track);
      };

      // 把本地媒体流传入轨道中
      let localStream = this.shareData.get('localMediaStream')
      localStream.getTracks().forEach(item => {
        offerPc.addTrack(item)
      })

      // 要创建这个channel 上面的onicecandidate才会自动触发(应该放在底部,但是会不生效)
      let dataChannel = offerPc.createDataChannel("MessageChannel");

      // 发送数据
      dataChannel.onopen = (e) => {
        dataChannel.send("hello RTC");
      };
      this.shareData.set("dataChannel", dataChannel);

      // 创建并发送offer sdp给对方(sdp描述指定连接本地端的属性，包括媒体格式)
      let offer = await offerPc.createOffer();
      socket.emit("offer", {
        receiver: receiver,
        sender: this.sender,
        offer: offer,
      });
      await offerPc.setLocalDescription(new RTCSessionDescription(offer));
    },
    // 2.接收者 接收offer
    async receiveOffer() {
      socket.on("offer", async (data) => {        
        let answerPc = new RTCPeerConnection();
        let localStream = this.shareData.get("localMediaStream");
        localStream.getTracks().forEach((item) => {
          answerPc.addTrack(item);
        });
        this.shareData.set("answerPc", answerPc);

        let remoteStream = this.shareData.get("remoteMediaStream");
        answerPc.ontrack = (e) => {
          remoteStream.addTrack(e.track);
        };
        answerPc.onicecandidate = (e) => {
          
          if (e.candidate) {
            socket.emit("answerIce", {
              receiver: data.sender,
              ice: e.candidate,
            });
          }
        };

        // 接收数据
        answerPc.ondatachannel = (e) => {
          let dataChannel = e.channel;
          dataChannel.onmessage = (ev) => {
            console.log("收到消息:", ev.data);
          };
        };

        await answerPc.setRemoteDescription(
          new RTCSessionDescription(data.offer)
        );
        let answer = await answerPc.createAnswer();
        socket.emit("answer", {
          answer: answer,
          receiver: data.sender,
        });
        await answerPc.setLocalDescription(new RTCSessionDescription(answer));
      });
    },
    // 3.发送者 接收应答answer
    receiveAnswer() {
      socket.on("answer", async (data) => {
        let offerPc = this.shareData.get("offerPc");
        offerPc.setRemoteDescription(new RTCSessionDescription(data.answer));
      });
    },
    // 6.发送者 接收answerIce
    receiveAnswerOfferIce() {
      socket.on("answerIce", async (data) => {
        let offerPc = this.shareData.get('offerPc')
        
        await offerPc.addIceCandidate(new RTCIceCandidate(data.ice))
      });
    },

    // 5.接收者 接收offerIce
    receiveOfferIce() {
      socket.on("offerIce", async (data) => {
        console.log('接收者offerIce',data);
        
        let answerPc = this.shareData.get('answerPc')
        await answerPc.addIceCandidate(new RTCIceCandidate(data.ice))
      });
    },
  },
};
</script>

<style lang='less' scoped>
.user {
  line-height: 50px;
  width: 200px;
}
.user:hover {
  background-color: rgb(0, 119, 255);
}
</style>
